import React, { Component } from 'react';
import "../styles/Register.scss"
import * as service from "../api/index";
import {Link,withRouter} from 'react-router-dom'
import { Toast } from 'antd-mobile'


class Register extends Component {
    constructor(props) {
        super(props);
        this.state = {
            phone: '',
            pass: '',
            pass2: ''
        }
    }
    handleChange(e) {
        this.setState({ [e.target.name]: e.target.value })
    }
    async register() {
        if (this.state.pass && this.state.phone && this.state.pass2) {
            if (this.state.pass == this.state.pass2) {
                var res = await service.user_login();
                var i = res.data.find((item)=>{return item.phone == this.state.phone});
                if(i){
                    Toast.show({
                        content: '用户已经存在！'
                    })
                }
                var res2 = await service.user_register({ phone: this.state.phone, pass: this.state.pass });
                if(res2.status == 201){
                    Toast.show({
                        content: '注册成功'
                    })
                    this.props.history.push('/login');
                }else{
                    Toast.show({
                        content: '注册失败'
                    })
                }
            }else{
                Toast.show({
                    content: '两次输入密码不相同！'
                })
            }
        } else {
            Toast.show({
                content: '请输入用户信息'
            })
        }
    }
    render() {
        return (
            <div className='register'>
                <div className="logo"><div></div></div>
                <div className="title">注册</div>
                <div className="box">
                    <input
                        type="text"
                        name='phone'
                        value={this.state.phone}
                        onChange={(e) => { this.handleChange(e) }}
                        placeholder='请输入手机号码'
                    />
                    <input
                        type="password"
                        name='pass'
                        value={this.state.pass}
                        onChange={(e) => { this.handleChange(e) }}
                        placeholder='请输入密码'
                    />
                    <input
                        type="password"
                        name='pass2'
                        value={this.state.pass2}
                        onChange={(e) => { this.handleChange(e) }}
                        placeholder='请重复密码'
                    />
                    <button onClick={() => { this.register() }}>立即注册</button>
                    <span><Link to="/login">已有帐号，去登录</Link></span>
                </div>
            </div>
        );
    }
}

export default withRouter(Register);